/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Exercicio1;

import java.util.AbstractQueue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.DelayQueue;

/**
 *
 * @author Pedro
 */
public class Channel {

    private final int TamBuffer = 100;
    private int buffer[] = new int[TamBuffer];
    private int posicoesCheias = 0, lido = 0, escrito = 0;

    public synchronized void send(int x) {
        while (posicoesCheias == TamBuffer) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }

        buffer[escrito] = x;


        posicoesCheias++;


        escrito = (escrito + 1) % TamBuffer;
        notifyAll();
    }

    public synchronized int receive() {
        while (posicoesCheias == 0) {
            try {

                wait();
            } catch (InterruptedException e) {
            }
        }
        int aux;
        aux = buffer[lido];


        posicoesCheias--;


        lido = (lido + 1) % TamBuffer;
        notifyAll();

        return aux;
    }
}

